package top.fengyulou.xiaofeng.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.fengyulou.xiaofeng.common.Jr;
import top.fengyulou.xiaofeng.common.UuidUtil;
import top.fengyulou.xiaofeng.domain.User;
import top.fengyulou.xiaofeng.dto.UserDto;
import top.fengyulou.xiaofeng.mapper.UserMapper;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @ClassName UserService
 * @Description TODO
 * @Author qwer
 * @Date 2021/8/22 1:54
 * @Version 1.0
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    //分页查询
    public void list(UserDto userDto) {
        //查询数据
        PageHelper.startPage(userDto.getPageNumber(), userDto.getPageSize());
        List<UserDto> list = userMapper.list(userDto);
        PageInfo<UserDto> pageInfo = new PageInfo<>(list);

        //返回结果
        userDto.setTotal(pageInfo.getTotal());
        userDto.setRows(list);
    }

    //根据id查询
    public UserDto getById(String id) {
        return userMapper.getById(id);
    }

    //保存
    public Jr save(User user) {
        UserDto userDto = userMapper.getByLn(user);
        if (StringUtils.isNotBlank(user.getId())) {
            if (ObjectUtils.isNotEmpty(userDto) && !userDto.getId().equals(user.getId())) {
                return Jr.nom("账号已存在");
            } else {
                update(user);
            }
        } else {
            if (ObjectUtils.isNotEmpty(userDto)) {
                return Jr.nom("账号已存在");
            } else {
                user.setId(UuidUtil.getShortUuid());
                user.setCreateTime(new Date());
                user.setCreateUserId(user.getCurrentUserId());
                userMapper.insert(user);
            }
        }
        return Jr.yes();
    }

    public void update(User user) {
        user.setUpdateTime(new Date());
        user.setLastUpdateUserId(user.getCurrentUserId());
        userMapper.update(user);
    }

    //删除
    public void delete(String[] ids) {
        userMapper.delete(ids);
    }
}
